﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using docmgr.BLL;

namespace docmgr.WinForm
{

    public partial class UserForm : DockContent
    {

        #region 预置基本参数开始
        private string PowerItemName = "User";

        //--表格结构
        private const string TableName = "User";
        //--表格主键标识
        string ID = "0";
        //--表格字段结构
                // 表的字段结构
        string[] tbfelids = new string[]{
		"ID,int,ID",
		"Username,varchar,用户名",
		"Password,varchar,密码",
		"DepartmentID,int,部门id",
		"PositionID,int,岗位id",
		"Remark,varchar,备注",
		"Name,varchar,姓名"};


        //操作员 (当前登录用户)        
        string OpManage = "YCSK";//Common.curUser.UserCode;

        //-- 声明业务对象
        docmgr.BLL.User bll;

        docmgr.BLL.Department departmentBll;
        docmgr.BLL.Position positionBll;

        //-- 创建数据源
        DataSet mainDs = new DataSet();
        DataTable modelDt = new DataTable();

        /// <summary>
        /// 窗体初始化结束标志
        /// </summary>
        bool IsWinInitOver = false;
        /// <summary>
        /// 是否已经绑定过表单控件
        /// </summary>
        bool IsCtrlBinded = false;

        #endregion

        #region 构造函数 、Load()、Shown()事件
        public UserForm()
        {
            InitializeComponent();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

            initWindow();
        }
        public UserForm(string ID)
        {
            InitializeComponent();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

            initWindow();
            this.ID = ID;
        }


        private void UserForm_Load(object sender, EventArgs e)
        {
            //if (!string.IsNullOrEmpty(ID)){}
            //--填充表单(初始化modelDt表格列结构)
            FillForm(ID);
            //--绑定表格数据源
            BindGrid();
        }
        private void UserForm_Shown(object sender, EventArgs e)
        {
            //窗体初始化结束标志
            IsWinInitOver = true;
        }
        #endregion

        #region 自定义初始化窗体 initWindow

        public void initWindow()
        {           
            //-- 创建业务对象
            bll = new docmgr.BLL.User();
            departmentBll = new Department();
            positionBll = new Position();

            IDNumericUpDown.Visible = false;
            initDepcomboBox();
            initPoscomboBox();
        }
        //设置窗体快捷键
        private void form_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (!e.Control)
                return;

            switch (e.KeyCode)
            {
                case Keys.N://新建
                    this.tsbtnNew_Click(this.tsbtnNew, null);
                    break;
                case Keys.S://搜索
                    this.tsbtnSave_Click(this.tsbtnSave, null);
                    break;
                case Keys.D://删除
                    this.tsbtnDel_Click(this.tsbtnDel, null);
                    break;
 		case Keys.W://关闭窗口
                    this.tsbtnClose_Click(this.tsbtnDel, null);
                    break;
                case Keys.H://显示帮助
                    this.tsbtnHelp_Click(this.tsbtnHelp, null);
                    break;
            }
        }
        #endregion

        #region 表格操作 绑定表格BindGrid,单元格单击事件
        /// <summary>
        /// 绑定Grid表格
        /// </summary>
        void BindGrid()
        {
            mainDs.Tables.Clear();
            mainDs.Tables.Add(bll.GetList("0=0"));
            this.bindingSource2.DataSource = mainDs.Tables[0];
            this.dataGridView1.DataSource = this.bindingSource2;
            //加载表格样式
            Common.LoadGridStyleByXML(this.Name, dataGridView1);
        }
        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //DataGridView gdsender = (DataGridView)sender;
                DataGridView.HitTestInfo info = dataGridView1.HitTest(e.Location.X, e.Location.Y);
                if (info.ColumnIndex > -1)
                {
                    if (info.RowIndex > -1)
                        dataGridView1.CurrentCell = dataGridView1.Rows[info.RowIndex].Cells[info.ColumnIndex];
                    Point point = this.PointToClient(new Point(e.X, e.Y));
                    Common.showContextMenu(dataGridView1, point, this.Name, false, false);
                }
            }

        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > -1 && e.RowIndex > -1)
            {
                this.ID = dataGridView1.Rows[e.RowIndex].Cells["ColumnID"].Value.ToString();
                FillForm(this.ID);
            }
        }
        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            this.ID = dataGridView1.Rows[e.RowIndex].Cells["ColumnID"].Value.ToString();
            FillForm(this.ID);
        }
        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
        }
        #endregion

        #region -- 主工具栏操作 新建、保存、删除、显示帮助
        //重置表单
        private void tsbtnNew_Click(object sender, EventArgs e)
        {
            //if (!Common.getUserAccess(this.PowerItemName, opType.bDelete)) {
            //    MessageBox.Show(this, "没有操作权限", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            //ResetForm();

            if (CheckForm())
            {
                //通过验证,提交表单      
                if (AddForm())
                    BindGrid();//提交成功重新绑定表格
            }
        }
        //提交表单
        protected void tsbtnSave_Click(object sender, EventArgs e)
        {
            //if (!Common.getUserAccess(this.PowerItemName, opType.bEdit)) {
            //    MessageBox.Show(this, "没有操作权限", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            if (CheckForm())
            {
                //通过验证,提交表单      
                if (SubmitForm())
                    BindGrid();//提交成功重新绑定表格
            }
        }

        //删除当前记录
        private void tsbtnDel_Click(object sender, EventArgs e)
        {
            //if (!Common.getUserAccess(this.PowerItemName, opType.bDelete)) {
            //    MessageBox.Show(this, "没有操作权限", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            DataRowView modelView = this.bindingSource1.Current as DataRowView;
            if (modelView != null)
            {
                string key = modelView["ID"].ToString();
                if (DialogResult.OK == MessageBox.Show(this, "确定要删除该条记录？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
                {
                    if (bll.DeleteByKey(key) > 0)
                    {
                        ResetForm();
                        BindGrid();
                        //弹出反馈消息
                        MessageBox.Show(this, "删除成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(this, "删除失败", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }
	//关闭窗口
        private void tsbtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //显示帮助
        private void tsbtnHelp_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region -- 主要业务:填充表单、重置表单、提交表单、验证表单

        /// <summary>
        /// 填充表单
        /// </summary>
        /// <param name="id"></param>
        private void FillForm(string key)
        {
            modelDt = bll.GetModel(key);
            if (modelDt.Rows.Count == 0)//行数虽为0,单表格结构已被初始化
            {
                modelDt.Rows.Add(1);//添加一个空行
                //可以设置空行各列的默认值
                //-
                modelDt.Rows[0]["ID"] = this.ID;//设置主键默认值
            }
            this.bindingSource1.DataSource = modelDt;
            //--数据绑定
            if (!IsCtrlBinded)
            {
                this.IDNumericUpDown.DataBindings.Add(new System.Windows.Forms.Binding("Value",this.bindingSource1,"ID",true));
				this.UsernameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text",this.bindingSource1,"Username",true));
				this.PasswordTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text",this.bindingSource1,"Password",true));
				this.DepcomboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue",this.bindingSource1,"DepartmentID",true));
                this.PoscomboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.bindingSource1, "PositionID", true));
				this.RemarkTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text",this.bindingSource1,"Remark",true));
				this.NameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text",this.bindingSource1,"Name",true));

                //--
                IsCtrlBinded = true;
            }
        }
        /// <summary>
        /// 重置表单
        /// </summary>
        private void ResetForm()
        {
            this.ID = "0";//重置主键
            if (modelDt.Columns.Count == 0)//modelDt表格还没初始化过
            {
                FillForm(this.ID);//填充表单,为了初始化modelDt表格的列结构
            }
            else
            {
                modelDt.Rows.Clear();//清除原有行
                modelDt.AcceptChanges();
                //-
                modelDt.Rows.Add(1);//添加一个空行              
                //可以设置空行各列的默认值             
                modelDt.Rows[0]["ID"] = this.ID;//设置主键默认值
            }
        }


        /// <summary>
        /// 提交表单
        /// </summary>
        private bool AddForm()
        {
            if (this.modelDt.GetChanges() == null)
            {
                //弹出反馈消息
                MessageBox.Show(this, "没有任何修改,无需保存", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            //StringBuilder opmsg = new StringBuilder();

            DataTable _chgTable = this.modelDt.GetChanges();

            _chgTable.Columns.Remove("ID");

            int result = bll.Update(_chgTable);
            if (result > 0)
            {

                //接受更新结果,刷新主键
                //this.modelDt.AcceptChanges();
                this.modelDt = _chgTable;//重新赋值才可以获取的ID 
                _chgTable.Columns.Add(new DataColumn("ID"));
                this.ID = "0";// this.modelDt.Rows[0]["ID"].ToString();
                //重新绑定
                //modelDt = bll.GetModel(this.ID);
                this.bindingSource1.DataSource = modelDt;
                //弹出反馈消息
                MessageBox.Show(this, "保存主记录成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return true;
            }
            else
            {
                MessageBox.Show(this, "保存主记录失败", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }


        /// <summary>
        /// 提交表单
        /// </summary>
        private bool SubmitForm()
        {
            if (this.modelDt.GetChanges() == null)
            {
                //弹出反馈消息
                MessageBox.Show(this, "没有任何修改,无需保存", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            //StringBuilder opmsg = new StringBuilder();

            DataTable _chgTable = this.modelDt.GetChanges();

            //_chgTable.Columns.Remove("ID");

            int result = bll.Update(_chgTable);
            if (result > 0)
            {

                //接受更新结果,刷新主键
                //this.modelDt.AcceptChanges();
                this.modelDt = _chgTable;//重新赋值才可以获取的ID 
                //_chgTable.Columns.Add(new DataColumn("ID"));
                this.ID = "0";// this.modelDt.Rows[0]["ID"].ToString();
                //重新绑定
                //modelDt = bll.GetModel(this.ID);
                this.bindingSource1.DataSource = modelDt;
                //弹出反馈消息
                MessageBox.Show(this, "保存主记录成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return true;
            }
            else
            {
                MessageBox.Show(this, "保存主记录失败", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        /// <summary>
        /// 验证表单
        /// </summary>
        /// <returns></returns>
        private bool CheckForm()
        {
            this.bindingSource1.EndEdit();//一定要先结束表单编辑状态

            string err;
                        if(FormValidate.CheckInput(this.IDNumericUpDown.Value,"int","",out err)){
					MessageBox.Show(this,"ID[数据类型:int] 输入验证错误！\r\n"+err,"输入数据错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
					this.IDNumericUpDown.Focus();
					return  false;
            }
            if(FormValidate.CheckInput(this.UsernameTextBox.Text,"string","",out err)){
					MessageBox.Show(this,"用户名[数据类型:string] 输入验证错误！\r\n"+err,"输入数据错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
					this.UsernameTextBox.Focus();
					return  false;
            }
            if(FormValidate.CheckInput(this.PasswordTextBox.Text,"string","",out err)){
					MessageBox.Show(this,"密码[数据类型:string] 输入验证错误！\r\n"+err,"输入数据错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
					this.PasswordTextBox.Focus();
					return  false;
            }
            if (FormValidate.CheckInput(this.DepcomboBox.SelectedValue, "int", "", out err))
            {
					MessageBox.Show(this,"部门id[数据类型:int] 输入验证错误！\r\n"+err,"输入数据错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
					this.DepcomboBox.Focus();
					return  false;
            }
            if (FormValidate.CheckInput(this.PoscomboBox.SelectedValue, "int", "", out err))
            {
					MessageBox.Show(this,"岗位id[数据类型:int] 输入验证错误！\r\n"+err,"输入数据错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
					this.PoscomboBox.Focus();
					return  false;
            }
            if(FormValidate.CheckInput(this.RemarkTextBox.Text,"string","√",out err)){
					MessageBox.Show(this,"备注[数据类型:string] 输入验证错误！\r\n"+err,"输入数据错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
					this.RemarkTextBox.Focus();
					return  false;
            }
            if(FormValidate.CheckInput(this.NameTextBox.Text,"string","√",out err)){
					MessageBox.Show(this,"姓名[数据类型:string] 输入验证错误！\r\n"+err,"输入数据错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
					this.NameTextBox.Focus();
					return  false;
            }

            return true;
        }

        #endregion

        private void DepcomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            


        }

        private void PoscomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        private void DepcomboBox_Click(object sender, EventArgs e)
        {
            

        }

        private void PoscomboBox_Click(object sender, EventArgs e)
        {
            
        }

        void initPoscomboBox()
        {
            DataSet xx = new DataSet();
            xx.Tables.Clear();
            xx.Tables.Add(positionBll.GetList("1=1"));
            this.PoscomboBox.DataSource = xx.Tables[0];
            this.PoscomboBox.DisplayMember = "Name";
            this.PoscomboBox.ValueMember = "ID";
        }

        void initDepcomboBox()
        {
            DataSet xx = new DataSet();
            xx.Tables.Clear();
            xx.Tables.Add(departmentBll.GetList("1=1"));
            this.DepcomboBox.DataSource = xx.Tables[0];
            this.DepcomboBox.DisplayMember = "Name";
            this.DepcomboBox.ValueMember = "ID";
        }

        private void resetStripButton1_Click(object sender, EventArgs e)
        {
            ResetForm();
        }
    }
}